package com.ds.smartstudio.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ds.smartstudio.common.Constants;
import com.ds.smartstudio.common.Result;
import com.ds.smartstudio.controller.DTO.UserDTO;

import com.ds.smartstudio.entity.User;
import com.ds.smartstudio.service.UserService;
import com.ds.smartstudio.utils.TokenUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.validation.Valid;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yangsf
 * @since 2022-07-02 10:42:24
 */
@RestController
@RequestMapping("/smartstudio/user")
@Slf4j
public class UserController {
    @Autowired
    UserService userService;
    @ApiOperation("user实体")
    @RequestMapping(method = RequestMethod.HEAD)
    public User user() {
        return new User();
    }

    @ApiOperation(value = "分页查询", notes = "根据页码和页面大小和name查询user，模糊匹配user的name，name在不搜索时为空字符串（默认），此方法可以在搜索功能和分页展示上使用，返回一个数组,第一个元素是当页所需要的user数组,第二个元素是当前条件的总记录数")
    @GetMapping
    public List selectPage(@ApiParam(value = "当前页码", required = true)
                             @RequestParam int page,
                             @ApiParam(value = "页面大小", required = true)
                             @RequestParam int pageSize,
                             @ApiParam("用户名称")
                             @RequestParam(defaultValue = "")  String name) {
        return userService.userPage(page, pageSize, name);
    }

    @ApiOperation("该方法用于添加用户，返回一个bool值")
    @PostMapping
    public Boolean addUser(@ApiParam(value = "需要一个User实体", required = true) @Valid @RequestBody User user) {
        return userService.save(user);
    }

    @ApiOperation("该方法用于编辑用户，返回一个bool值")
    @PutMapping
    public Boolean updateUser(@ApiParam(value = "需要一个User实体", required = true) @RequestBody User user) {
        return userService.updateById(user);
    }

    @ApiOperation("该方法用于删除用户，返回一个bool值")
    @DeleteMapping
    public Boolean deleteUser(@ApiParam(value = "需要一个User实体", required = true) @RequestBody User user) {
        return userService.removeById(user);
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        Result result;
        if (StrUtil.isBlank(userDTO.getUsername()) || StrUtil.isBlank(userDTO.getPassword())) {
            result = Result.error(Constants.CODE_400, "用户名或密码不能为空");
        }
        userDTO = userService.login(userDTO);
        if (userDTO == null) {
            result = Result.error(Constants.CODE_401, "用户名或密码错误");
        } else {
            result = Result.succeed(userDTO);
        }
        return result;
    }

    @PostMapping("/signUp")
    public Result signUp(@RequestBody UserDTO userDTO) {
        Result result;
        if (userDTO == null || StrUtil.isBlank(userDTO.getUsername()) || StrUtil.isBlank(userDTO.getPassword()) || StrUtil.isBlank(userDTO.getConfirmPassword()) || StrUtil.isBlank(userDTO.getEmail())) {
            result = Result.error(Constants.CODE_400, "不要乱搞");
        } else if (!userDTO.getPassword().equals(userDTO.getConfirmPassword())) {
            result = Result.error(Constants.CODE_400, "两次密码不一致，再次提醒不要乱搞");
        } else {
            User user = new User();
            user.setDsUserEmail(userDTO.getEmail());
            user.setDsUserName(userDTO.getUsername());
            user.setDsUserPassword(userDTO.getPassword());
            user.setDsUserRole(1);
            try {
                userService.save(user);
                result = Result.succeed();
            } catch (Exception e) {
                log.error(e.toString());
                result = Result.error(Constants.CODE_500, "系统错误");
            }
        }
        return  result;
    }

    @PostMapping("/mine")
    public Result updateOne(@RequestBody User user) {
        Result result;
        try {
            userService.updateById(user);
            result = Result.succeed(user);
        } catch (Exception e) {
            result = Result.error(Constants.CODE_500, "系统错误");
        }
        return result;
    }

    @GetMapping("/mine")
    public Result selectOneByName() {
        Result result;
        User user = TokenUtils.getCurrentUser();
        if (user == null) {
            result = Result.error(Constants.CODE_500, "系统错误");
        } else {
            result = Result.succeed(user);
        }
        return result;
    }

    @GetMapping("/count")
    public Result countUser() {
        Result result;
        try {
            Integer cnt = userService.selectTotalByName("");
            result = Result.succeed(cnt);
        } catch (Exception e) {
            result = Result.error(Constants.CODE_500, e.toString());
        }
        return result;
    }

    @GetMapping("/verification")
    public String verification( @ApiParam("用户名称") @RequestParam(defaultValue = "")  String username)
    {

        List<User> list = userService.list();
        list.forEach(System.out::println);
        System.out.println(username);
        String str="";
        if(StrUtil.isBlank(username))
        {
            str="用户名不能为空";
        }
        else
        {
            for(User user: list)
            {
                if(username.equals(user.getDsUserName()))
                {
                    str="用户名已存在";
                    break;
                }
            }
        }
        Map<String, String> res = new HashMap<>();
        res.put("mag", str);
        return JSON.toJSONString(res);
    }


    @DeleteMapping("/removeAll")
    public Boolean removeAll( @ApiParam("用户名称") @RequestBody List<Integer> ids )
    {
        boolean b = userService.removeBatchByIds(ids);
        return b;
    }
}
